package com.aly.game.exe2lua.builder.impl;

import com.aly.game.exe2lua.builder.BaseExportBuilder;
import com.aly.game.exe2lua.enums.ExportConfig;
import com.aly.game.exe2lua.funcs.TypeConsumer;
import com.aly.game.exe2lua.objs.*;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * aly @ 16-11-12.
 */
public class CSVBuilder extends BaseExportBuilder {
    private Pattern p = Pattern.compile("\"");

    public CSVBuilder(ExportConfig type) {
        super(type);
    }

    @Override
    public void buildHeadLine0(StringBuilder builder, String saveFileName, TypedHeadInfo info) {
        for (HeadItem item : info) {
            builder.append('\"').append(item.cellVal).append('\"').append(',');
        }
        builder.append("\r\n");
    }

    @Override
    public void buildLine(StringBuilder builder, TypedHeadInfo headInfo, String id, LineObj line, boolean buildOne, Map<HeadItem, String> replaceVal) {
        for (HeadItem item : headInfo) {
//                String funType = head.getKey();
            String cellVal = line.getValue(item);
            if (cellVal.length() > 1) {
                if (cellVal.charAt(0) == '"' && cellVal.charAt(cellVal.length() - 1) == '"') {
                    cellVal = cellVal.substring(1, cellVal.length() - 1);
                }
            }
            Matcher matcher = p.matcher(cellVal);
            if (matcher.find()) {
                cellVal = matcher.replaceAll("\"\"");
                builder.append("\"").append(cellVal).append("\",");
            } else if (cellVal.contains(",")) {
                builder.append("\"").append(cellVal).append("\",");
            } else {
                builder.append(cellVal).append(",");
            }
        }
        builder.append("\r\n");
    }

    @Override
    public String getSaveFileName(Sheet sheet, String fileName) {
        return fileName;
    }

    @Override
    public void buildEnd(StringBuilder builder, TypedHeadInfo headInfo) {

    }

    @Override
    public HeadItem getIDHeadItem(TypedHeadInfo headInfo) {
        return null;
    }

    @Override
    public void parseHead(String typeAlia, String cellVal, TypeConsumer consumer) {
        if (typeAlia.length() > 0) {
            String[] typeAndName = typeAlia.split(",");
            String type = typeAndName[1];
            String name = typeAndName[0];
            consumer.onType(type, name);
        } else {
            if (cellVal.trim().length() > 0) {
                consumer.onType("", "");
            }
        }
    }
}

